package ifrn.scartissue.client;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import marauroa.client.BannedAddressException;
import marauroa.client.LoginFailedException;
import marauroa.client.TimeoutException;
import marauroa.common.net.InvalidVersionException;

public class ClientWindow extends JFrame {

	private LogonDialog logonDialog;
	private JTextField serverField;
	private JTextField userField;
	private JPasswordField passwordField;
	
	
	public ClientWindow() {
		
		setTitle("[2013-m-jogo] Cliente");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setMinimumSize(new Dimension(300, 200));
		
		createDialogs();
		createComponents();
		setVisible(true);
	}

	private void createComponents() {
		
		GridLayout layout = new GridLayout(4, 2);
		
		setLayout(layout);
		JLabel userLabel = new JLabel("usuário");
		userField = new JTextField();
		JLabel passwordLabel = new JLabel("senha");
		passwordField = new JPasswordField();
		JLabel serverLabel = new JLabel("servidor");
		serverField = new JTextField("127.0.0.1");
		JButton loginButton = new JButton("Login");
		
		loginButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				validateLogin();
			}
		});
		
		JButton logonButton = new JButton("Cadastrar");
		logonButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				MarauroaClient.get().setServer(serverField.getText());
				logonDialog.setVisible(true);
			}
		});
		
		add(serverLabel);
		add(serverField);
		add(userLabel);
		add(userField);
		add(passwordLabel);
		add(passwordField);
		add(loginButton);
		add(logonButton);
		pack();
	}
	
	private void createDialogs() {
		logonDialog = new LogonDialog();
		logonDialog.setModal(true);
	}
	
	private void validateLogin(){
		String user = userField.getText();
		String password = passwordField.getText();
		
		MarauroaClient client = MarauroaClient.get();
		client.setServer(serverField.getText());
		try {
			client.connect();
		} catch (IOException e) {
			alertError("Servidor não encontrado");
			return;
		}
		
		try {
			client.login(user, password);
		} catch (LoginFailedException e) {
			alertError("Erro: Login Inválido");
			return;
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			alertError("Erro");
			return;
		}
		
		alert("Logado com sucesso");
		Client.doLogin();
	}
	
	private void alert(String message) {
		JOptionPane.showMessageDialog(this, message);
	}
	
	private void alertError(String message) {
		JOptionPane.showMessageDialog(this, message, "Erro", JOptionPane.ERROR_MESSAGE);
	}
}
